package com.dd.census.controller;

import com.dd.census.controller.common.BaseController;
import com.dd.census.entity.Resume;
import com.dd.census.properties.Properties;
import com.dd.census.service.ResumeService;
import com.dd.census.tools.SysException;
import com.dd.census.tools.validator.ValidateUtil;
import com.dd.census.tools.validator.ValidateUtil.ValidationResult;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("rest/resume")
public class ResumeController extends BaseController  {
	private static final Logger logger = LoggerFactory.getLogger(ResumeController.class);
	@Autowired
	private ResumeService resumeService;
	@Autowired
	private Properties properties;

	@RequestMapping("selectPageResume")
	public ResponseEntity<Object> selectPageResume(@RequestBody Resume resume, HttpServletRequest request) {
		try {
			return this.doSuccess(request, resumeService.selectPageResume(resume));
		} catch (SysException e) {
			// 业务异常
			return doFaild(request, e);
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("insertResume")
	public ResponseEntity<Object> insertResume(HttpServletRequest request, @RequestParam(required = false,name = "file") MultipartFile file, @RequestParam(name = "dto")  String dto) {

		try {
			// 基本输入验证
			JSONObject jsonobject = JSONObject.fromObject(dto);
			Resume resume= (Resume)JSONObject.toBean(jsonobject,Resume.class);
			ValidationResult rscheck = ValidateUtil.validate(resume);
			// 系统时间字符串
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			if (file != null) {
				String type =request.getParameter("type");
				// 文件目录
				String systemName = System.getProperty("os.name");
				// 文件目录
				String disk = properties.getLocation();
				if(!StringUtils.isBlank(systemName) && systemName.toLowerCase().contains("linux")){
					disk = properties.getLinuxLocation();
				}
				// 系统时间字符串
				String dayString = sf.format(new Date());
				// 新文件目录
				String diskNew = disk + dayString + File.separator;
				// 系统时间目录不存在则创建
				File dir = new File(diskNew.replace("\\", "/"));
				if (!dir.exists())
					dir.mkdir();
				// 文件扩展名带.
				String skill = "";
				String region = "";
				String suffix = "";
				if(!StringUtils.isEmpty(resume.getSkill())){
					skill = resume.getSkill();
				}
				if(!StringUtils.isEmpty(resume.getRegion())){
					region = resume.getRegion();
				}
				// 不带后缀时不显示文件类型所以要获取后缀并拼接
                if(!StringUtils.isEmpty(resume.getLinkName())){
                    String []b = resume.getLinkName().split("\\.");
                    suffix = b[b.length - 1];
                }
				String name = resume.getName()+"-"+skill+"-"+region+"."+suffix;
				// 保存文件
				file.transferTo(new File(diskNew + name));
				String path =(File.separator + dayString + File.separator + name).replace("\\", "/");
				resume.setLinkName(name);
				resume.setLink(path);
			}
			if(!rscheck.isHasErrors()) {
				resume.setCreateUserId(this.getUserId(request));
				resume.setCreateTime(new Date());
				//因为addtime在数据库里为datetime类型的数据所以不能为空否则报错
				// 先判断是否为空 否则做.equals的时候会报错 如果不为空在继续走下面
				if(resume.getAddtime() == null || resume.getAddtime().isEmpty()){
					resume.setAddtime(sf.format(new Date()));
				}
				if(resume.getAddtime().equals("")){
					resume.setAddtime(sf.format(new Date()));
				}
				resumeService.insertResume(resume);
				return this.doSuccess(request);
			}else {
				return this.doSuccess(request,rscheck);
			}
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("/getResumeByID/{id}")
	public ResponseEntity<Object> getResumeByID(@PathVariable("id") String id, HttpServletRequest request) {
		try {
			return this.doSuccess(request, resumeService.selectResumeByKey(id));
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("updateResume")
	public ResponseEntity<Object> updateResume(HttpServletRequest request, @RequestParam(required = false,name = "file") MultipartFile file, @RequestParam(name = "dto")  String dto) {

		try {
			// 基本输入验证
			JSONObject jsonobject = JSONObject.fromObject(dto);
			Resume resume= (Resume)JSONObject.toBean(jsonobject,Resume.class);

			ValidationResult rscheck =ValidateUtil.validate(resume);
			if (file != null) {
				String type =request.getParameter("type");
				// 文件目录
				String systemName = System.getProperty("os.name");
				// 文件目录
				String disk = properties.getLocation();
				if(!StringUtils.isBlank(systemName) && systemName.toLowerCase().contains("linux")){
					disk = properties.getLinuxLocation();
				}
				// 系统时间字符串
				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
				String dayString = sf.format(new Date());
				// 新文件目录
				String diskNew = disk + dayString + File.separator;
				// 系统时间目录不存在则创建
				File dir = new File(diskNew.replace("\\", "/"));
				if (!dir.exists())
					dir.mkdir();
				// 文件扩展名带.
				String skill = "";
				String region = "";
                String suffix = "";
				if(!StringUtils.isEmpty(resume.getSkill())){
					skill = resume.getSkill();
				}
				if(!StringUtils.isEmpty(resume.getRegion())){
					region = resume.getRegion();
				}
                // 不带后缀时不显示文件类型所以要获取后缀并拼接
                if(!StringUtils.isEmpty(resume.getLinkName())){
                    String []b = resume.getLinkName().split("\\.");
                    suffix = b[b.length - 1];
                }
				String name = resume.getName()+"-"+skill+"-"+region+"."+suffix;;
				// 保存文件
				file.transferTo(new File(diskNew + name));
				String path =(File.separator + dayString + File.separator + name).replace("\\", "/");
				resume.setLinkName(name);
				resume.setLink(path);
			}
			resume.setUpdateUserId(this.getUserId(request));
			resume.setUpdateTime(new Date());
			if(!rscheck.isHasErrors()) {
 				resumeService.updateResume(resume);
				return this.doSuccess(request);
			}else {
				return this.doSuccess(request,rscheck);
			}
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	@RequestMapping("deleteResume")
	public ResponseEntity<Object> deleteResume(HttpServletRequest request, @RequestBody Resume resume) {

		try {
			resumeService.deleteResume(resume);

			return this.doSuccess(request);
		} catch (Exception e) {
			// 系统异常
			logger.error("Internal Server Error", e);
			return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
}
